package com.ldgk.pim.client.presenter;

import com.extjs.gxt.ui.client.widget.Info;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.ldgk.pim.client.event.PlaceEvent;
import com.ldgk.pim.client.event.PlaceEventHandler;
import com.ldgk.pim.client.util.Util;
import com.ldgk.pim.client.view.PlaceView;
import com.ldgk.pim.data.Place;

/**
 * Presenter that handles distribution places gui events
 * 
 * @version 1.0
 * 
 */
public class PlacePresenter implements Presenter {
	private PlaceView view;

	/**
	 * Default constructor
	 * 
	 * @param view
	 */
	public PlacePresenter(PlaceView view) {
		this.view = view;
		this.view.setPresenter(this);
		this.registerEventHandlers();
	}

	/**
	 * Saves a distribution place (insert/update)
	 * 
	 * @param place
	 *            - distribution place
	 */
	public void savePlace(final Place place) {
		Util.persistenceService.persist(place, new AsyncCallback<Void>() {
			public void onFailure(Throwable caught) {
				Window.alert("RPC to sendEmail() failed.");
			}

			public void onSuccess(Void result) {
				Util.mapView.addDistributionPlace(place);
				Info.display("Mensagem", "Dados atualizados!");
			}
		});
	}

	/**
	 * Deletes a distribution place
	 * 
	 * @param place
	 *            - distribution place
	 */
	public void deletePlace(Place place) {
		Util.persistenceService.delete(place, new AsyncCallback<Void>() {
			public void onFailure(Throwable caught) {
				Window.alert("RPC to sendEmail() failed.");
			}

			public void onSuccess(Void result) {
				Info.display("Mensagem", "Local excluido!");
			}
		});
	}

	private void registerEventHandlers() {
		Util.eventbus.addHandler(PlaceEvent.getType(), new PlaceEventHandler() {
			@Override
			public void addPlace(Place place) {
				view.editPlace(place);
			}

			@Override
			public void editPlace(Place place) {
				view.editPlace(place);
			}
		});
	}
}
